use crate::app::server::message::Message;
use crate::app::module::common::{CommonMsg,Result};
use serde::Serialize;

pub fn err_msg(status:i32, msgbody:&str, header:u16) ->Message{
    let cmsg= CommonMsg::default().set_status(status);
    let cmsg = cmsg.set_message(msgbody);
    match cmsg.to_message(header){
        Err(e)=>{Message::new(0,Vec::from(e))}
        Ok(o)=>{o}
    }
}
pub fn json_msg_err<T: Serialize>(msg:&T,header:u16)->(Message,Result<()>){
    let mut cmsg = CommonMsg::default().set_status(200);
    match cmsg.set_data_from_struct(msg){
        Err(e)=>{return (err_msg(500, &e, header), Err(e));}
        Ok(_)=>{
            match cmsg.to_message(header){
                Err(e)=>{return (err_msg(500, &e, header), Err(e));}
                Ok(o)=>{return (o,Ok(()))}
            }
        }
    }
}

pub fn json_msg_log<T: Serialize>(msg:&T,header:u16)->Message{
    let mut cmsg = CommonMsg::default().set_status(200);
    match cmsg.set_data_from_struct(msg){
        Err(e)=>{
            log_error_ln!("json_msg_log:{}",e);
            return err_msg(500, &e, header);}
        Ok(_)=>{
            match cmsg.to_message(header){
                Err(e)=>{
                    log_error_ln!("json_msg_log:{}",e);
                    return err_msg(500, &e, header);}
                Ok(o)=>{return o;}
            }
        }
    }
}

pub fn string_msg_log(msg:String,header:u16)->Message{
    let cmsg = CommonMsg::new(200, msg.as_bytes().to_vec());
    match cmsg.to_message(header){
        Err(e)=>{
            log_error_ln!("json_msg_log:{}",e);
            return err_msg(500, &e, header);}
        Ok(o)=>{return o;}
    }

}